<template>
  <div class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="liveFormRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="10">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="课程类型" prop="courseType">
              <el-cascader v-model="form.courseType" placeholder="请选择课程类型" :options="data.courseList" @change="changeCourseTypeHandle"
                           :props="{label:'name',value:'id',children:'children',emitPath:false}"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="类型" prop="type">
              <el-select clearable v-model="form.type" placeholder="请选择类型">
                <el-option v-for="item in data.liveTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="课程时间" prop="timeArray">
              <el-date-picker
                  v-model="form.timeArray"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="datetimerange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  @change="selectedTimerRangeHandle"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="老师" prop="teacherId">
              <el-select clearable filterable v-model="form.teacherId" placeholder="请选择老师">
                <el-option v-for="item in data.teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="资料" prop="docId">
              <el-select clearable filterable v-model="form.docId" placeholder="请选择资料">
                <el-option v-for="item in data.docList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="题库" prop="bankId">
              <el-select clearable filterable v-model="form.bankId" placeholder="请选择题库">
                <el-option v-for="item in data.bankList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="直播url" prop="url">
              <el-input v-model="form.url" placeholder="请输入url"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="说明">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入说明"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {addLive, editLive, getLiveDetail} from '@/api/resource/live'
import {listDictItemByCode} from '@/api/config/dic'
import {listTeacher} from '@/api/teacher'
import {listDoc} from '@/api/resource/doc'
import {listBank} from '@/api/resource/bank'
const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  liveTypeList: [],
  teacherList: [],
  docList: [],
  bankList: []
})
const form = reactive({
  id: null,
  orderNum: '',
  name: '',
  courseType: '',
  type: '',
  teacherId: '',
  docId: '',
  bankId: '',
  url: '',
  publishedFlag: 1,
  remark: '',
  timeArray: [],
  startTime: '',
  endTime: ''
})

const rules = ({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  courseType: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  // docId: [{ required: true, message: '请选择资料', trigger: 'blur' }],
  // bankId: [{ required: true, message: '请选择题库', trigger: 'blur' }],
  url: [{ required: true, message: '请输入url', trigger: 'blur' }],
  teacherId: [{ required: true, message: '请选择老师', trigger: 'blur' }],
  timeArray: [{ required: true, message: '请选择时间', trigger: 'blur' }],
  publishedFlag: [{ required: true, message: '请选择状态', trigger: 'blur' }],
})

// 详情
const initDetail = (row) => {
  getLiveDetail(row.id || route.query.id).then((res) => {
    Object.keys(form).forEach((key) => { form[`${key}`] = res.data[`${key}`] })
    form.timeArray = [form.startTime, form.endTime]
    initDataCourseType()
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'liveTypeCode'}).then(res => {
    data.liveTypeList = res.rows
  })
  listTeacher({}).then(res => {
    data.teacherList = res.rows
  })
  // listDoc({}).then(res => {
  //   data.docList = res.rows
  // })
  // listBank({}).then(res => {
  //   data.bankList = res.rows
  // })
}

const save = () => {
  proxy.$refs["liveFormRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {
        addLive(form).then(res => {
          if (res.code === 200) {
            clearForm()
            ElMessage.success('新增成功');
          }
        })
      } else {
        editLive(form).then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功');
          }
        })
      }
    }
  })
}
function selectedTimerRangeHandle(dateArr) {
  if (dateArr && dateArr.length > 0) {
    form.startTime = dateArr[0]
    form.endTime = dateArr[1]
  }
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}
function clearForm() {
  Object.keys(form).forEach((key)=>{
    form[key] = ''
  })
  form.publishedFlag = 1
}
function changeCourseTypeHandle() {
  form.docId = ''
  form.bankId = ''
  initDataCourseType()
}
const initDataCourseType = async () => {
  data.bankList = []
  let bankList = await listBank({courseType: form.courseType})
  data.bankList = bankList.rows
  data.docList = []
  let docList = await listDoc({courseType: form.courseType})
  data.docList = docList.rows
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  routeQuery.type == 'edit' ? '' : initDataCourseType()
  isAdd.value = routeQuery.type == 'add'
  initData()
})
// watch(() => { return form.courseType }, () => {
//   // 数据变化之后的回调函数
//   listDoc({courseType:form.courseType}).then(res => {
//     data.docList = res.rows
//   })
//   listBank({courseType:form.courseType}).then(res => {
//     data.bankList = res.rows
//   })
// }, { immediate: true, deep: false })
</script>
